from django.db import models

from libs.db import BaseModel
from libs.enums import ConnectionState, PartnerType, Authorizer


class Partner(BaseModel):
    type = models.CharField('类型', max_length=30, choices=PartnerType.choices(), default=PartnerType.ORG.value)
    name = models.CharField('企业名称', max_length=300)
    app_server = models.CharField('应用注册API', max_length=300, null=True, blank=True)
    system_app_key = models.CharField('系统内置应用Key', max_length=30, null=True, blank=True)
    detail = models.JSONField('互联合作方的信息', null=True, blank=True)
    remarks = models.CharField('备注', max_length=1000, blank=True, null=True, default='')


class Connection(BaseModel):
    partner = models.ForeignKey(Partner, related_name='connections', on_delete=models.CASCADE)
    state = models.CharField('状态', max_length=30, choices=ConnectionState.choices(), default=ConnectionState.ONGOING.value)
    start_time = models.DateTimeField('有效期开始时间', null=True, blank=True)
    end_time = models.DateTimeField('有效期结束时间', null=True, blank=True)
    latest_pull_data_at = models.DateTimeField('最后拉取数据时间', null=True, blank=True)
    # 可能是通过第三方平台创建的，记录第三方平台信息
    thirdparty_app = models.ForeignKey(Partner, related_name='created_connections', null=True, blank=True, on_delete=models.SET_NULL)
    thirdparty_id = models.IntegerField('第三方应用的实体id', null=True, blank=True)

    class Meta:
        verbose_name = '互联'
        verbose_name_plural = '互联'
        ordering = ('-id',)


class Certificate(BaseModel):
    connection = models.ForeignKey(Connection, related_name='certificates', on_delete=models.CASCADE)
    url = models.CharField('授权书文件地址', max_length=300)
    source_data = models.JSONField('授权原始数据', null=True, blank=True)
    data = models.JSONField('授权书数据', null=True, blank=True)
    start_time = models.DateTimeField('有效期开始时间', blank=True, null=True)
    end_time = models.DateTimeField('有效期结束时间', blank=True, null=True)
    server = models.CharField('服务地址', max_length=300)
    public_key = models.TextField('非对称加密-公钥')
    second_key = models.TextField('对称加密-密钥')
    holder_open_id = models.CharField('持有者open_id', max_length=500)
    authorizer = models.CharField('授权方', max_length=30, choices=Authorizer.choices(), default=Authorizer.OUR_SIDE.value)
    validated = models.BooleanField('是否验证通过', default=False)
    is_voided = models.BooleanField('是否作废', default=False)

    class Meta:
        verbose_name = '授权书'
        verbose_name_plural = '授权书'
        ordering = ('-id',)
